/*
 * @(#)InMemorySourceCompiler.java	1.0 Feb 9, 2009
 *
 *	The MIT License
 *
 *	Copyright (c) 2008 Malachi de AElfweald <malachid@gmail.com>
 *
 *	Permission is hereby granted, free of charge, to any person obtaining a copy
 *	of this software and associated documentation files (the "Software"), to deal
 *	in the Software without restriction, including without limitation the rights
 *	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *	copies of the Software, and to permit persons to whom the Software is
 *	furnished to do so, subject to the following conditions:
 *
 *	The above copyright notice and this permission notice shall be included in
 *	all copies or substantial portions of the Software.
 *
 *	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 *	THE SOFTWARE.
 */
package org.eoti.util;

import com.sun.org.apache.bcel.internal.classfile.Code;

import javax.tools.*;
import java.util.concurrent.*;
import java.util.*;
import java.net.URI;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

// Derived from http://www.java2s.com/Tutorial/Java/0120__Development/CompilingfromMemory.htm

public class InMemorySourceCompiler
{
	protected JavaCompiler compiler;
	protected DiagnosticCollector<JavaFileObject> diagnostics;
	protected ConcurrentHashMap<String,Code> codes;
	protected CopyOnWriteArrayList<String> options;

	public InMemorySourceCompiler()
	{
		compiler = ToolProvider.getSystemJavaCompiler();
		diagnostics = new DiagnosticCollector<JavaFileObject>();
		codes = new ConcurrentHashMap<String,Code>();
	}

	public void addSource(String name, CharSequence source)
	{
		codes.put(name, new Code(name, source));
	}

	public void addOption(String option)
	{
		if(options == null) options = new CopyOnWriteArrayList<String>();
		options.add(option);
	}

	public boolean compile(boolean debug)
	{
		Iterable<? extends JavaFileObject> compilationUnits = codes.values();
		JavaCompiler.CompilationTask task = compiler.getTask(
				null,				// Writer out
				null,				// JavaFileManager fileManager
				diagnostics,		// DiagnosticListener<? extends JavaFileObject> diagnosticListener   
				options,			// Iterable<String> options (like "-target" "1.5")
				null,				// Iterable<String> classes
				compilationUnits	// Iterable<JavaFileObject> compilationUnits
		);
		boolean success = task.call();
		if(debug)
		{
			for(Diagnostic diagnostic : diagnostics.getDiagnostics())
			{
				System.out.println(diagnostic.getCode());
				System.out.println(diagnostic.getKind());
				System.out.println(diagnostic.getPosition());
				System.out.println(diagnostic.getStartPosition());
				System.out.println(diagnostic.getEndPosition());
				System.out.println(diagnostic.getSource());
				System.out.println(diagnostic.getMessage(null));
			}

			System.out.println(success ? "Success" : "Failure");
		}

		if(success)
		{
			for(String name : codes.keySet())
			{
				Code code = codes.get(name);
				try{
					code.clz = Class.forName(name);
					codes.put(name, code);
				} catch(Exception e){
					if(debug)
					{
						System.err.format("Exception: %s\n", e.getMessage());
						e.printStackTrace();
					}
				}
			}
		}

		return success;
	}

	public Class getCompiledClass(String name)
	{
		return codes.get(name).getCompiledClass();
	}

	class Code extends SimpleJavaFileObject
	{
		protected String name;
		protected CharSequence source;
		protected Class clz;

		protected Code(String name, CharSequence source)
		{
			super(URI.create("string:///" + name.replace('.','/') + Kind.SOURCE.extension),Kind.SOURCE);
			this.name = name;
			this.source = source;
		}

		public CharSequence getCharContent(boolean ignoreEncodingErrors)
		throws IOException{return source;}

		public Class getCompiledClass(){return clz;}
	}
}
